package com.rainbow.service.impl;


import com.alibaba.fastjson.JSON;
import com.rainbow.dao.OrderDao;
import com.rainbow.domain.Order;
import com.rainbow.domain.Product;
import com.rainbow.service.OrderService;
import com.rainbow.service.ProductService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

//import org.apache.rocketmq.spring.core.RocketMQTemplate;
//import org.springframework.messaging.support.MessageBuilder;

@Service
@Slf4j
public class OrderServiceImpl5 implements OrderService {
    @Autowired
    private OrderDao orderDao;
    // feigin 负载均衡
    @Autowired
    private ProductService productService;
//    ribbon 负载均衡
    @Autowired
    private RestTemplate restTemplate;
//    @Autowired
//    private RocketMQTemplate rocketMQTemplate;

//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public Order createOrder(Integer pid)  {
        // 1.查询商品
        // 省略校验
        log.info("接受到{}号商品下单,下面查询商品信息",pid);

//        Product product = restTemplate.getForObject("http://service-product/product/" + pid,Product.class);
        Product product = productService.findByPid(pid);
        // 2.下单
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderDao.save(order);


        // 3.扣减库存
//        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
//        postParameters.add("pid", pid);
//        postParameters.add("number", 1);
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Content-Type", "application/x-www-form-urlencoded");
//        HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
//        restTemplate.postForObject("http://service-product/product/sale",r,String.class);
        productService.sale(pid,1);

        log.info("创建订单成功, {}", JSON.toJSONString(order));
        // 4,投递下单成功 rocketMQ
        // 暂时不用了
        return order;
    }

    @Override
    public void createOrder(Order order) {

    }
}
